//
//  DLDatabaseListVC.m
//  AllPass
//
//  Created by apple on 2021/11/1.
//

#import "DLDatabaseListVC.h"
#import <ACActionSheet/ACActionSheet.h>
#import "DLCreateDataBaseVC.h"
#import "DLPasswordInputVC.h"
#import "DLGroupListController.h"
#import "DLDatabaseListCell.h"
#import "GCDWebUploader.h"
#import "GCDWebServerDataResponse.h"
#import "SJXCSMIPHelper.h"
#import "DLDataWifiInfoView.h"
#import "DLWebView.h"
@interface DLDatabaseListVC () <GCDWebUploaderDelegate,DLDataWifiInfoViewDelegate>{
    GCDWebUploader* _webServer;
}
@property(nonatomic,retain)NSMutableArray * databaseFiles, * keyFiles;
@end

@implementation DLDatabaseListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.rightBtnImage = Image(@"添加_首页");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveDatabaseOrKeyfiles) name:ReceiveDatabaseFromOtherApplication object:nil];
    self.databaseFiles = [NSMutableArray new];
    self.keyFiles = [NSMutableArray new];
    [self createUI];
    [self updateFiles];
}
-(void)receiveDatabaseOrKeyfiles{
    [self.databaseFiles removeAllObjects];
    [self.keyFiles removeAllObjects];
    [self updateFiles];
}
- (void)updateFiles {
    NSString *documentsDirectory = [Mytools documentsDirectory];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *dirContents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
    
    NSMutableArray *files = [[NSMutableArray alloc] init];
    for (NSString *file in dirContents) {
        NSString *path = [documentsDirectory stringByAppendingPathComponent:file];
        
        BOOL dir = NO;
        [fileManager fileExistsAtPath:path isDirectory:&dir];
        if (!dir) {
            [files addObject:file];
        }
    }
    [files sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    NSArray *databaseFilenames = [files filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self ENDSWITH[c] '.kdb') OR (self ENDSWITH[c] '.kdbx')"]];
    NSArray *keyFilenames = [files filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"!((self ENDSWITH[c] '.kdb') OR (self ENDSWITH[c] '.kdbx'))"]];
    for (NSString * name in databaseFilenames) {
        DLDatabaseListCellModel * mo = [DLDatabaseListCellModel new];
        mo.name = name;
        [self.databaseFiles addObject:mo];
    }
    for (NSString * name in keyFilenames) {
        DLDatabaseListCellModel * mo = [DLDatabaseListCellModel new];
        mo.name = name;
        [self.keyFiles addObject:mo];
    }
    NSArray * arr = nil;
    if (self.databaseFiles.count == 0 && self.keyFiles.count == 0) {
        arr = @[];
    }else{
        arr = @[@""];
    }
    [Mytools NeedResetNoViewWithView:self.myTab andArr:arr];
    [self.myTab reloadData];
}
- (void)rightBtnClick{
    ACActionSheet *actionSheet = [[ACActionSheet alloc] initWithTitle:nil cancelButtonTitle:NSLocalizedString(@"cancel", nil) destructiveButtonTitle:nil otherButtonTitles:@[NSLocalizedString(@"Import or Export", nil),NSLocalizedString(@"create new database", nil),NSLocalizedString(@"How to use", nil)] actionSheetBlock:^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [self wifiClick];
        }else if (buttonIndex == 1){
            DLCreateDataBaseVC * vc = [DLCreateDataBaseVC new];
            vc.createFinishBlock = ^{
                [self.databaseFiles removeAllObjects];
                [self.keyFiles removeAllObjects];
                [self updateFiles];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }else if (buttonIndex == 2){
            DLWebView * vc = [DLWebView new];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
    [actionSheet show];
}
-(void)wifiClick{
    NSString *documentsDirectory = [Mytools documentsDirectory];
    _webServer = [[GCDWebUploader alloc] initWithUploadDirectory:documentsDirectory];
    // 设置代理
    _webServer.delegate = self;
    _webServer.allowHiddenItems = YES;
    
    // 限制文件上传类型
    _webServer.allowedFileExtensions = @[@"kdb", @"kdbx", @"key"];
    // 设置网页标题
    _webServer.title = NSLocalizedString(@"All Pass", nil);
    // 设置展示在网页上的文字(开场白)
    _webServer.prologue = @"welcome";
    // 设置展示在网页上的文字(收场白)
    _webServer.epilogue = @"无记制作";    
    if ([_webServer start]) {
        [self showWifiInfoView];
        NSLog(@"%@",[NSString stringWithFormat:@"请在网页输入这个地址  http://%@:%zd/", [SJXCSMIPHelper deviceIPAdress], _webServer.port]);
    } else {
        XHQHUDErrorText(NSLocalizedString(@"WiFi sync failed, please check if you are connected to the current LAN", nil));
    }
}
-(void)showWifiInfoView{
    NSString * content = [NSString stringWithFormat:@"%@ http://%@:%zd/",NSLocalizedString(@"Please enter this website at your browser", nil), [SJXCSMIPHelper deviceIPAdress], _webServer.port];
    DLDataWifiInfoView * v = [[DLDataWifiInfoView alloc]initWithFrame:Frame(0, -kTopHeight, SCREEN_WIDTH, kTopHeight) content:content];
    v.delegate = self;
    [self.view addSubview:v];
    [UIView animateWithDuration:0.35 delay:0 usingSpringWithDamping:0.3 initialSpringVelocity:15 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        v.y = 0;
    } completion:nil];
}
- (void)breakWifi:(DLDataWifiInfoView *)infoView{
    [UIView animateWithDuration:0.35 delay:0 usingSpringWithDamping:0.3 initialSpringVelocity:15 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        infoView.y = -kTopHeight;
    } completion:^(BOOL finished) {
        [infoView removeFromSuperview];
        [self->_webServer stop];
        self->_webServer = nil;
    }];
}
#pragma mark - <GCDWebUploaderDelegate>
- (void)webUploader:(GCDWebUploader*)uploader didUploadFileAtPath:(NSString*)path {
    DLLog(@"[UPLOAD] %@", path);
    [self wifiAction];
}
- (void)webUploader:(GCDWebUploader*)uploader didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath {
    DLLog(@"[MOVE] %@ -> %@", fromPath, toPath);
    [self wifiAction];
}
- (void)webUploader:(GCDWebUploader*)uploader didDeleteItemAtPath:(NSString*)path {
    DLLog(@"[DELETE] %@", path);
    [self wifiAction];
}
- (void)webUploader:(GCDWebUploader*)uploader didCreateDirectoryAtPath:(NSString*)path {
    DLLog(@"[CREATE] %@", path);
    [self wifiAction];
}
-(void)wifiAction{
    [self receiveDatabaseOrKeyfiles];
}
-(void)createUI{
    self.myTab = [[UITableView alloc]initWithFrame:Frame(0, kTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT - kTopHeight) style:UITableViewStyleGrouped];
    self.myTab.delegate = self;
    self.myTab.dataSource = self;
    [self.view addSubview:self.myTab];
}
#pragma mark 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.databaseFiles.count > 0 && self.keyFiles.count > 0) {
        return 2;
    }else if(self.databaseFiles.count == 0 && self.keyFiles.count == 0){
        return 0;
    }else{
        return 1;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        if (self.databaseFiles.count > 0) {
            return self.databaseFiles.count;
        }
    }
    return self.keyFiles.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DLDatabaseListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"DLDatabaseListCell"];
    if (!cell) {
        cell = [[DLDatabaseListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DLDatabaseListCell"];
    }
    if (indexPath.section == 0) {
        if (self.databaseFiles.count > 0) {
            if (indexPath.row < self.databaseFiles.count) {
                DLDatabaseListCellModel * mo = self.databaseFiles[indexPath.row];
                cell.model = mo;
            }
        }else{
            [self keyfilesModelConfig:cell idx:indexPath];
        }
    }else{
        [self keyfilesModelConfig:cell idx:indexPath];
    }
    MJWeakSelf
    cell.cellDoneBlock = ^{
        [weakSelf.databaseFiles removeAllObjects];
        [weakSelf.keyFiles removeAllObjects];
        [weakSelf updateFiles];
    };
    return cell;
}
-(void)keyfilesModelConfig:(DLDatabaseListCell * )cell idx:(NSIndexPath*)indexPath{
    if (indexPath.row < self.keyFiles.count) {
        DLDatabaseListCellModel * mo = self.keyFiles[indexPath.row];
        cell.model = mo;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (self.databaseFiles.count > 0) {
            if (indexPath.row < self.databaseFiles.count) {
                DLDatabaseListCellModel * mo = self.databaseFiles[indexPath.row];
                return mo.cellHeight;
            }
        }
    }
    if (indexPath.row < self.keyFiles.count) {
        DLDatabaseListCellModel * mo = self.keyFiles[indexPath.row];
        return mo.cellHeight;
    }
    return 45;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0){
        if (self.databaseFiles.count > 0) {
            return 40;
        }
    }
    if (self.keyFiles.count > 0) {
        return 40;
    }
    return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 0){
        if (self.databaseFiles.count > 0) {
            return [self createHeadView:YES];
        }
    }
    if (self.keyFiles.count > 0) {
        return [self createHeadView:NO];
    }
    return nil;
}
-(UIView *)createHeadView:(BOOL)isDataBase{
    UIView * v = [UIView new];
    v.backgroundColor = UnderLineColor;
    NSString * name = isDataBase ? NSLocalizedString(@"Database", nil):NSLocalizedString(@"KeyFiles", nil);
    UILabel * lab = [UILabel labelWithTitle:name color:TextColor fontSize:18];
    [v addSubview:lab];
    lab.sd_layout.leftSpaceToView(v, 10).centerYEqualToView(v).heightIs(20);
    [lab setSingleLineAutoResizeWithMaxWidth:300];
    return v;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        if (indexPath.row < self.databaseFiles.count) {
            NSDictionary * enterDic = [DLUserDefault userDefaultsModel].eneterPswDic;
            DLDatabaseListCellModel * mo = self.databaseFiles[indexPath.row];
            id obj = enterDic[mo.name];
            NSString * psw = nil;
            if (obj) {
                psw = (NSString*)obj;
            }
            NSString *documentsDirectory = [Mytools documentsDirectory];
            NSString *path = [documentsDirectory stringByAppendingPathComponent:mo.name];
            if ([psw containsString:@".key"]) {
                //密钥文件
                NSString * keyfilePath = [documentsDirectory stringByAppendingPathComponent:psw];
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if (![fileManager fileExistsAtPath:keyfilePath]) {
                    XHQHUDErrorText(NSLocalizedString(@"Key file was deleted, app can not open database", nil));
                    return;
                }
                DatabaseDocument *db = [[DatabaseDocument alloc] initWithFilename:path password:nil keyFile:keyfilePath];
                [self gotoGroupVC:db];
            }else{
                //密码
                if (psw.length > 0) {
                    DatabaseDocument *db = [[DatabaseDocument alloc] initWithFilename:path password:psw keyFile:nil];
                    [self gotoGroupVC:db];
                }else{
                    DLPasswordInputVC * vc = [DLPasswordInputVC new];
                    vc.dbName = mo.name;
                    vc.enterBlock = ^(DatabaseDocument * _Nonnull db) {
                        [self gotoGroupVC:db];
                    };
                    [self presentViewController:vc animated:YES completion:nil];
                }
            }
        }
    }else{
        
    }
}
-(void)gotoGroupVC:(DatabaseDocument *)db{
    if (db.kdbTree) {
        VicSingleObject * single = [VicSingleObject getInstance];
        single.db = db;
        DLGroupListController * vc = [DLGroupListController new];
        vc.group= db.kdbTree.root;//最外层的group
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        XHQHUDErrorText(NSLocalizedString(@"Decryption failed, please check if the password is correct or if you are using the key file to decrypt", nil));
    }
}

@end
